package com.zhlq.export.service.impl;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.web.multipart.MultipartFile;

import com.zhlq.export.service.ExportService;
import com.zhlq.util.ConfigUtil;
import com.zhlq.util.CreateFileUtil;

public class ExportServiceImpl implements ExportService {

	@Override
	public File fileToDisk(MultipartFile file) {
		// 旧文件名
		String oldFileName = file.getOriginalFilename();
		// 后缀名
		String suffix = oldFileName.substring(oldFileName.lastIndexOf("."));
		Date now = new Date();
		// 新文件名
		String newFileName =  new SimpleDateFormat("yyyyMMddHHmmssSSS").format(now) + suffix;
		// 年
		String year = new SimpleDateFormat("yyyy").format(now);
		// 月
		String month = new SimpleDateFormat("MM").format(now);
		//日
		String day = new SimpleDateFormat("dd").format(now);
		// excel根目录路径
		String excelRoot = ConfigUtil.get("excelRoot").trim();
		// 文件父目录路径
		String path = excelRoot +year+File.separator+month+File.separator+day+File.separator;
		// 文件路径
		String filePath = path + newFileName ;
System.out.println(filePath);
		FileOutputStream fileOutputStream = null;
		File diskFile;
		try {
			// 文件
			diskFile = new File(filePath);
			CreateFileUtil.createFile(diskFile.getPath());
			fileOutputStream = new FileOutputStream(diskFile);
			fileOutputStream.write(file.getBytes());
			fileOutputStream.flush();
		} catch (IOException e) {
			throw new RuntimeException(e);
		} finally {
			if(null != fileOutputStream){
				try {
					fileOutputStream.close();
				} catch (IOException e) {
					throw new RuntimeException(e);
				}
			}
		}
		return diskFile;
	}

}
